package com.hhxy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.hhxy.constants.SystemConstants;
import com.hhxy.handler.exception.CustomException;
import com.hhxy.model.dto.AddUserDto;
import com.hhxy.model.dto.ChangeUserStatusDto;
import com.hhxy.model.entity.Role;
import com.hhxy.model.entity.User;
import com.hhxy.model.vo.UserInfoAndRoleIdsVo;
import com.hhxy.service.RoleService;
import com.hhxy.service.UserService;
import com.hhxy.utils.SecurityUtils;
import com.hhxy.utils.response.AppHttpCodeEnum;
import com.hhxy.utils.response.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * @author ghp
 * @date 2023/5/5
 * @title
 * @description
 */
@Api(tags = {"后端接口", "用户管理", "系统管理"})
@ApiSupport(author = "ghp", order = 1)
@RestController
@RequestMapping("/system/user")
@Validated
public class BeUserController {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @GetMapping("/list")
    @ApiOperation(value = "分页条件查询用户信息")
    @ApiOperationSupport(author = "ghp", order = 1)
    @ApiImplicitParams({@ApiImplicitParam(name = "pageNum", value = "当前页码", dataTypeClass = Integer.class, required = true), @ApiImplicitParam(name = "pageSize", value = "每页大小", dataTypeClass = Integer.class, required = true), @ApiImplicitParam(name = "userName", value = "账号"), @ApiImplicitParam(name = "phonenumber", value = "手机号"), @ApiImplicitParam(name = "status", value = "状态")})
    public ResponseResult list(@NotNull(message = "pageNum不能为空") Integer pageNum, @NotNull(message = "pageSize不能为空") Integer pageSize, String userName, String phonenumber, String status) {
        return userService.list(pageNum, pageSize, userName, phonenumber, status);
    }

    @PutMapping("/changeStatus")
    @ApiOperation(value = "修改用户状态")
    @ApiOperationSupport(author = "ghp", order = 1)
    public ResponseResult changeStatus(@RequestBody @Valid ChangeUserStatusDto changeUserStatusDto) {
        boolean flag = userService.update(new LambdaUpdateWrapper<User>()
                .eq(User::getId, changeUserStatusDto.getUserId())
                .set(User::getStatus, changeUserStatusDto.getStatus()));
        if (!flag) {
            throw new CustomException(AppHttpCodeEnum.SERVICE_UPDATE_ERROR);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS_UPDATE);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据用户id查询用户信息和角色信息")
    @ApiOperationSupport(author = "ghp", order = 1)
    @ApiImplicitParam(name = "id", value = "用户id", required = true)
    public ResponseResult getUserAndRoleById(@PathVariable Long id) {
        // 查询所有的角色信息（角色状态必须正常）
        List<Role> roles = roleService.list(new LambdaQueryWrapper<Role>()
                .eq(Role::getStatus, SystemConstants.ROLE_NORMAL));
        // 根据userId查询出用户信息
        User user = userService.getById(id);
        // 查询当前用户所具有的角色id列表
        List<Long> roleIds = roleService.selectRoleIdByUserId(id);

        // 封装VO
        UserInfoAndRoleIdsVo vo = new UserInfoAndRoleIdsVo(user, roles, roleIds);
        return ResponseResult.okResult(vo);
    }

    @PutMapping
    @ApiOperation(value = "修改用户信息")
    @ApiOperationSupport(author = "ghp", order = 1)
    public ResponseResult updateUserInfoById(@RequestBody User user) {
        // TODO 这里偷个懒，没有封装DTO了
        return userService.updateUserInfoById(user);
    }

    @PostMapping
    @ApiOperation(value = "新增用户信息")
    @ApiOperationSupport(author = "ghp", order = 1)
    public ResponseResult add(@RequestBody @Valid AddUserDto addUserDto) {
        return userService.addUser(addUserDto);
    }

    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除用户信息")
    @ApiOperationSupport(author = "ghp", order = 1)
    public ResponseResult deleteUserByIds(@PathVariable Long[] ids) {
        if (Arrays.asList(ids).contains(SecurityUtils.getUserId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.CLIENT_USERDELETE_ERROR);
        }
        boolean flag = userService.removeByIds(Arrays.asList(ids));
        if (!flag) {
            throw new CustomException(AppHttpCodeEnum.SERVICE_DELETE_ERROR);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS_DELETE);
    }


}
